import { change_platform, doctor_platform_select } from '@/services/instiution';
import { EditOutlined, LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { history, useModel } from '@umijs/max';
import { message, Select, Spin } from 'antd';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, { useCallback, useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import ChangePassword from '../ChangePassword';
import HeaderDropdown from '../HeaderDropdown';
import PersonalData from '../PersonalData';

export type GlobalHeaderRightProps = {
  menu?: boolean;
  children?: React.ReactNode;
};

export const AvatarName = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  return <span className="anticon">{currentUser?.username}</span>;
};

export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu, children }) => {
  /**
   * 退出登录，并且将当前的 url 保存
   */
  const loginOut = async () => {
    localStorage.removeItem('loginToken');
    const { search, pathname } = window.location;
    const urlParams = new URL(window.location.href).searchParams;
    /** 此方法会跳转到 redirect 参数所在的位置 */
    const redirect = urlParams.get('redirect');
    // Note: There may be security issues, please note
    if (window.location.pathname !== '/login' && !redirect) {
      history.replace({
        pathname: '/login',
        // search: stringify({
        //   redirect: pathname,
        // }),
      });
    }
  };
  const actionClassName = useEmotionCss(({ token }) => {
    return {
      display: 'flex',
      height: '48px',
      marginLeft: 'auto',
      overflow: 'hidden',
      alignItems: 'center',
      padding: '0 8px',
      cursor: 'pointer',
      borderRadius: token.borderRadius,
      '&:hover': {
        backgroundColor: token.colorBgTextHover,
      },
    };
  });
  const { initialState, setInitialState } = useModel('@@initialState');
  // 个人资料/密码
  const [editpassword, seteditpassword] = useState(false);
  const [userinfo, setuserinfo] = useState(false);

  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if (key === 'logout') {
        flushSync(() => {
          setInitialState((s) => ({ ...s, currentUser: undefined }));
        });
        loginOut();
        return;
      }
      if (key === 'userinfo') {
        setuserinfo(true);
        return;
      }
      if (key === 'password') {
        seteditpassword(true);
        return;
      }
    },
    [setInitialState],
  );

  const loading = (
    <span className={actionClassName}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { currentUser } = initialState;

  if (!currentUser || !currentUser.username) {
    return loading;
  }

  const menuItems = [
    ...(menu
      ? [
          {
            key: 'center',
            icon: <UserOutlined />,
            label: '个人中心',
          },
          {
            key: 'settings',
            icon: <SettingOutlined />,
            label: '个人设置',
          },
          {
            type: 'divider' as const,
          },
        ]
      : []),
    {
      key: 'userinfo',
      icon: <UserOutlined />,
      label: '个人资料',
    },
    {
      key: 'password',
      icon: <EditOutlined />,
      label: '修改密码',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];
  const [platformList, setPlatformList] = useState<any>(undefined);
  // 获取机构列表
  useEffect(() => {
    const get_doctor_platform_select = async () => {
      let res: any = await doctor_platform_select();
      console.log('切换机构', res);
      let arr: any = [];
      res.data?.map((item: any) => {
        let lemp: any = {};
        lemp.label = item.name;
        lemp.value = item.id;
        arr.push(lemp);
      });
      setPlatformList(arr);
    };
    get_doctor_platform_select();
  }, []);

  // 机构切换的回调事件
  const handleChange = async (value: string) => {
    console.log(`selected ${value}`);
    let request_body = {
      id: value,
    };
    let res: any = await change_platform(request_body);
    if (res.msg == 'ok') {
      message.success('机构切换成功！');
      setTimeout(() => {
        location.replace('/welcome');
      }, 500);
    } else {
      message.error(res.msg);
    }
  };

  return (
    <>
      {platformList && platformList.length > 0 ? (
        <Select
          defaultValue={currentUser.current_platform.name}
          style={{ width: 200 }}
          onChange={handleChange}
          options={platformList}
        ></Select>
      ) : (
        <></>
      )}
      <HeaderDropdown
        menu={{
          selectedKeys: [],
          onClick: onMenuClick,
          items: menuItems,
        }}
      >
        {children}
      </HeaderDropdown>
      {!userinfo ? (
        ''
      ) : (
        <PersonalData
          // editId={editId}
          userinfo={userinfo}
          setuserinfo={setuserinfo}
          // actionRef={actionRef}
        ></PersonalData>
      )}
      {!editpassword ? (
        ''
      ) : (
        <ChangePassword
          // editId={editId}
          editpassword={editpassword}
          seteditpassword={seteditpassword}
          // actionRef={actionRef}
        ></ChangePassword>
      )}
    </>
  );
};
